const express = require('express')
// 生成ID
const { v4: uuidv4 } = require('uuid')
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt');
const multer = require('multer');
let fs = require('fs')
const config = require('../../config/baseinfo')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
const router = express.Router()
// 一级路由： /user
// 二级路由： /register
// http://127.0.0.1:3005/user/register
// 导入已封装的数据函数
const db = require('../../config/db.js')
const dayjs = require('dayjs');

// 导入用户逻辑
const userController = require('../../controllers/UserController.js')
// 设置路由
router.post('/avatar', userController.upload)

// 处理图片
// 通过filename属性定制
let storage = multer.diskStorage({
    // 保存的路径
    destination: function (req, file, callback) {
        callback(null, 'public/images/')
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
});
//生成的图片放入uploads文件夹下
let upload = multer({
    storage: storage
})
// 保存头像到后台
router.post('/modify_avatar', upload.single('file'), function (req, res) {
    let file = req.file
    console.log(file);
    if (!file) {
        res.send({
            code: -1,
            msg: '上传失败'
        })
    }
    else {
        res.send({
            data: {
                code: 200,
                success: true,
                msg: '上传成功',
                file: file
            }
        })
    }

})

//把头像路径保存到数据库
router.get('/avatar_sql', function (req, res) {
    // 请求需要进行token校验 
    let token = req.query.token;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    // 接收前端的参数
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    } else {
        // 接收前端的文件
        let file = req.query.file
        // 定义存在在服务器的图片的路径（存在数据库的路径）
        let image = `${HostUrl}/static/upload/${file.filename}`
        let id = result.data;
        let user_check_sql = "select * from user where id='" + id + "'";
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败'
                })
            } else {
                if (rows && rows.length != 0) {
                    var user_update_sql = "update user set avatar = '" + image + "' where  id = '" + id + "'";
                    db.query(user_update_sql, function (err, rows) {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: "修改失败"
                            });
                        } else {
                            res.send({
                                code: 200,
                                msg: "修改头像成功",
                                success: true,
                                avatar: image
                            });
                        }
                    });
                }
            }
        })
    }
})

//把轮播图路径保存到数据库
router.post('/carousel', function (req, res) {
    // 请求需要进行token校验 
    console.log(req.body);
    let token = req.headers.etoken;
    let image = req.body.image;
    let imgname = req.body.imgname;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    let id = dayjs().valueOf();
    // 接收前端的参数
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    } else {
        // 接收前端的文件
        var user_update_sql = 'insert into Carousel(imgname,image,id) values(' + '"' + imgname + '"' + ',' + '"' + image + '"' + ',' + '"' + id + '"' + ')';
        db.query(user_update_sql, function (err, rows) {
            if (err) {
                res.send({
                    code: -1,
                    msg: "添加失败"
                });
            } else {
                res.send({
                    data: {
                        code: 200,
                        msg: "添加成功",
                        success: true,
                    }
                });
            }
        });
    }
})

//获取轮播图
router.get('/carousel', function (req, res) {
    // 前端接收参数
    let id = req.query.id;
    // 请求需要进行token校验 
    // console.log("id", id);
    let user_check_sql;
    if(id){
        user_check_sql = 'select * from carousel where id = "' + id + '"';
    }else{
        user_check_sql = 'select * from carousel';
    }
    // console.log(user_check_sql);
    // 查询用户表
    //  user_check_sql = 'select * from department';
    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            // console.log(rows);
            // let [{ userName, gender, jobnumber, phone, avatar }] = rows;
            // console.log(typeof avatar);
            res.send({
                data: {
                    code: 200,
                    msg: '获取成功',
                    success: true,
                    data: {
                        result: rows
                    }
                },
                success: true,
            })
        }
    })
});

// 修改轮播图
router.put('/carousel', function (req, res) {
    // 请求需要进行token校验 
    console.log(req.headers);
    console.log(req.body);
    let token = req.headers.etoken;
    let image = req.body.image;
    let imgname = req.body.imgname;
    let id = req.body.id;
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    console.log(result.data);
    // 接收前端的参数
    if (result == 'err') {
        res.status(401).send({
            code: 3002,
            msg: '登录已过期,请重新登录'
        })
    } else {
        
        let user_check_sql = "select * from carousel where id='" + id + "'";
        db.query(user_check_sql, (err, rows) => {
            if (err) {
                res.send({
                    code: -1,
                    msg: '查询失败',
                    err
                })
            } else {
                if (rows && rows.length != 0) {
                    var user_update_sql = "update carousel set imgname = '" + imgname + "',image = '" + image + "' where  id = '" + id + "'";
                    db.query(user_update_sql, function (err, rows) {
                        if (err) {
                            res.send({
                                code: -1,
                                msg: "设置失败",
                                err
                            });
                        } else {
                            res.send({
                                data: {
                                    code: 200,
                                    msg: "设置成功",
                                    success: true,
                                }
                            });
                        }
                    });
                }
            }
        })
    }
})

// 删除轮播图数据
router.delete('/delete', function (req, res) {
    console.log(req.query);
    let jobnumber = req.query.jobnumber;
    let id = req.query.id;
    let classifyId = req.query.classifyId;
    // console.log(jobnumber);
    // "delete from  数据表 where 字段 = '" + 值 + "'"
    // let sql;
    // if (id) {
    //     sql = 'delete from Departmentinfo where id = "' + id + '"';
    // }
    //  else if (jobnumber) {
    //     sql = 'delete from User where jobnumber = "' + jobnumber + '"';
    // }
    //  else if (classifyId) {
    //     sql = 'delete from Departmentclassify where id = "' + classifyId + '"';
    // }
    let sql = 'delete from Carousel where id = "' + id + '"';
    db.query(sql, function (err) {
        if (err) {
            res.send({
                code: -1,
                msg: '删除失败',
                err,
            })
        } else {
            res.send({
                data: {
                    code: 200,
                    msg: '删除成功',
                    success: true,
                }
            })
        }
    })

})

module.exports = router;
